<template>
  <div class="recording-management-page">
    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="客户端">
          <el-select
            v-model="filterForm.clientId"
            placeholder="请选择客户端"
            clearable
            @change="loadRecordings"
            style="width: 200px;"
          >
            <el-option label="全部" value="" />
            <el-option
              v-for="client in clientList"
              :key="client.id"
              :label="client.name"
              :value="client.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="录制时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="loadRecordings"
          />
        </el-form-item>

        <el-form-item label="文件大小">
          <el-select
            v-model="filterForm.sizeFilter"
            placeholder="请选择"
            clearable
            @change="loadRecordings"
            style="width: 150px;"
          >
            <el-option label="全部" value="" />
            <el-option label="小于100MB" value="small" />
            <el-option label="100MB-500MB" value="medium" />
            <el-option label="大于500MB" value="large" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadRecordings" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="showSettingsDialog">
            <el-icon><Setting /></el-icon>
            存储设置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 录屏记录列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><VideoCamera /></el-icon>
            录屏记录列表
          </span>
          <div class="header-actions">
            <el-button type="danger" :disabled="selectedRecordings.length === 0" @click="batchDelete">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>

          </div>
        </div>
      </template>

      <el-table
        :data="recordingList"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="fileName" label="文件名" min-width="200">
          <template #default="{ row }">
            <div class="file-info">
              <el-icon class="file-icon"><VideoPlay /></el-icon>
              <span>{{ row.fileName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="clientName" label="客户端" width="120" />
        <el-table-column prop="startTime" label="录制开始时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="时长" width="100">
          <template #default="{ row }">
            {{ formatDuration(row.duration) }}
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="文件大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="270" fixed="right" align="center" header-align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="playRecording(row)">
                <el-icon><VideoPlay /></el-icon>
                播放
              </el-button>
              <el-button size="small" @click="downloadRecording(row)">
                <el-icon><Download /></el-icon>
                下载
              </el-button>
              <el-button type="danger" size="small" @click="deleteRecording(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadRecordings"
          @current-change="loadRecordings"
        />
      </div>
    </el-card>

    <!-- 视频播放对话框 -->
    <el-dialog v-model="playDialogVisible" title="录屏播放" width="80%" center>
      <div class="video-player">
        <video
          ref="videoPlayerRef"
          :src="currentVideoUrl"
          controls
          preload="metadata"
          crossorigin="anonymous"
          playsinline
          webkit-playsinline
          style="width: 100%; height: 500px; background-color: #000;"
          @loadstart="onVideoLoadStart"
          @loadedmetadata="onVideoLoadedMetadata"
          @loadeddata="onVideoLoadedData"
          @canplay="onVideoCanPlay"
          @error="onVideoError"
        >
          <source :src="currentVideoUrl" type="video/mp4">
          您的浏览器不支持视频播放
        </video>
        <div v-if="videoStatus" class="video-status" style="margin-top: 10px; color: #666;">
          状态: {{ videoStatus }}
        </div>
      </div>
    </el-dialog>

    <!-- 存储设置对话框 -->
    <el-dialog v-model="settingsDialogVisible" title="录屏存储设置" width="600px">
      <el-form :model="storageSettings" label-width="120px">
        <el-form-item label="存储路径">
          <el-input
            v-model="storageSettings.storagePath"
            placeholder="请输入存储路径"
          >
            <template #prepend>
              <el-icon><Folder /></el-icon>
            </template>
            <template #append>
              <el-button @click="selectStoragePath">
                获取默认
              </el-button>
            </template>
          </el-input>
          <div style="margin-top: 5px; color: #909399; font-size: 12px;">

          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="settingsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStorageSettings">保存设置</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  VideoCamera, Search, Setting, Delete, Refresh, VideoPlay, Download, Folder
} from '@element-plus/icons-vue'
import api, { filesAPI, clientsAPI, systemAPI } from '@/services/api'

// 响应式数据
const loading = ref(false)
const playDialogVisible = ref(false)
const settingsDialogVisible = ref(false)
const videoPlayerRef = ref(null)
const currentVideoUrl = ref('')
const videoStatus = ref('')
const selectedRecordings = ref([])

// 筛选表单
const filterForm = reactive({
  clientId: '',
  dateRange: null,
  sizeFilter: ''
})

// 客户端列表
const clientList = ref([])

// 录屏记录列表
const recordingList = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 存储设置
const storageSettings = reactive({
  storagePath: '由服务端配置'
})

// 加载录屏记录
const loadRecordings = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize
    }

    // 添加筛选条件
    if (filterForm.clientId) {
      params.clientId = filterForm.clientId
    }

    if (filterForm.dateRange && filterForm.dateRange.length === 2) {
      params.startDate = filterForm.dateRange[0].toISOString()
      params.endDate = filterForm.dateRange[1].toISOString()
    }

    // 调用真实API
    const response = await filesAPI.getRecordings(params)

    if (response.code === 200) {
      recordingList.value = response.data.list.map(item => {
        return {
          id: item.id,
          fileName: item.fileName,
          clientId: item.clientId,
          clientName: item.clientName,
          startTime: new Date(item.startTime).toLocaleString(),
          endTime: item.endTime ? new Date(item.endTime).toLocaleString() : null,
          duration: item.duration,
          fileSize: item.fileSize,
          status: item.status,
          url: `/api/v1/files/recordings/${item.id}`,
          filePath: item.filePath
        }
      })
      pagination.total = response.data.total
    } else {
      throw new Error(response.message || '获取录屏列表失败')
    }
  } catch (error) {
    console.error('加载录屏记录失败:', error)
    ElMessage.error('加载录屏记录失败')
    recordingList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 格式化时长
const formatDuration = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    recording: 'warning',
    completed: 'success',
    failed: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    recording: '录制中',
    completed: '已完成',
    failed: '录制失败'
  }
  return texts[status] || '未知'
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRecordings.value = selection
}

// 播放录屏
const playRecording = async (recording) => {
  if (recording.status !== 'completed') {
    ElMessage.warning('只能播放已完成的录屏文件')
    return
  }

  try {
    // 直接使用文件路径，转换为相对于静态文件服务的路径
    let videoPath = recording.filePath

    // 标准化路径分隔符（Windows使用\，需要转换为/）
    videoPath = videoPath.replace(/\\/g, '/')

    // 将绝对路径转换为相对路径
    if (videoPath.includes('storage/recordings/')) {
      videoPath = videoPath.replace(/.*storage\/recordings\//, '/recordings/')
    } else if (videoPath.includes('recordings/')) {
      videoPath = videoPath.replace(/.*recordings\//, '/recordings/')
    } else {
      // 如果路径格式不符合预期，使用文件名
      videoPath = `/recordings/${recording.fileName}`
    }

    // 重置视频状态
    videoStatus.value = '准备播放...'

    // 先清空URL，然后设置新URL，强制重新加载
    currentVideoUrl.value = ''
    playDialogVisible.value = true

    // 等待对话框打开
    await nextTick()

    // 设置视频URL
    currentVideoUrl.value = videoPath

    // 再次等待DOM更新
    await nextTick()

    // 如果视频元素存在，手动触发加载
    if (videoPlayerRef.value) {
      videoPlayerRef.value.load()
    }

  } catch (error) {
    ElMessage.error('视频加载失败：' + error.message)
  }
}

// 下载录屏
const downloadRecording = async (recording) => {
  if (recording.status !== 'completed') {
    ElMessage.warning('只能下载已完成的录屏文件')
    return
  }

  try {
    // 使用axios下载文件，确保包含认证头
    const downloadPath = recording.url.replace('/api/v1', '')

    // 显示下载进度
    ElMessage.info('正在准备下载...')

    const response = await api.get(downloadPath, {
      responseType: 'blob',
      timeout: 60000, // 60秒超时
      onDownloadProgress: (progressEvent) => {
        if (progressEvent.total) {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        }
      }
    })

    // 现在响应拦截器已修复，应该能正确获取到response.data
    const blob = response.data;

    if (!blob) {
      throw new Error('下载的文件为空 - 响应数据为空')
    }

    if (!(blob instanceof Blob)) {
      throw new Error('下载的文件格式不正确')
    }

    // 检查Blob大小
    if (blob.size === 0) {
      throw new Error('下载的文件为空 - 文件大小为0')
    }

    // 创建下载链接，确保正确的MIME类型
    const contentType = response.headers['content-type'] || blob.type || 'video/mp4'

    // 如果需要重新创建Blob以确保正确的MIME类型
    const finalBlob = blob.type === contentType ? blob : new Blob([blob], { type: contentType })

    const url = window.URL.createObjectURL(finalBlob)

    const link = document.createElement('a')
    link.href = url
    link.download = recording.fileName
    link.style.display = 'none'
    document.body.appendChild(link)

    link.click()
    document.body.removeChild(link)

    // 延迟释放URL，确保下载完成
    setTimeout(() => {
      window.URL.revokeObjectURL(url)
    }, 1000)

    ElMessage.success('录屏文件下载成功')
  } catch (error) {
    console.error('下载录屏失败:', error)
    if (error.response) {
      ElMessage.error(`下载失败：${error.response.status} ${error.response.statusText}`)
    } else {
      ElMessage.error('下载失败：' + error.message)
    }
  }
}

// 视频事件处理函数
const onVideoLoadStart = () => {
  videoStatus.value = '开始加载...'
}

const onVideoLoadedMetadata = (event) => {
  const video = event.target
  videoStatus.value = `元数据已加载 (${video.videoWidth}x${video.videoHeight}, ${Math.round(video.duration)}秒)`
}

const onVideoLoadedData = () => {
  videoStatus.value = '数据已加载'
}

const onVideoCanPlay = () => {
  videoStatus.value = '准备就绪'
}

const onVideoError = (event) => {
  const video = event.target
  const error = video.error
  if (error) {
    let errorMsg = '未知错误'
    switch (error.code) {
      case 1:
        errorMsg = '视频加载被中止'
        break
      case 2:
        errorMsg = '网络错误'
        break
      case 3:
        errorMsg = '视频解码错误'
        break
      case 4:
        errorMsg = '视频格式不支持'
        break
    }
    videoStatus.value = `错误: ${errorMsg}`
    ElMessage.error(`视频播放失败: ${errorMsg}`)
  }
}

// 删除录屏
const deleteRecording = async (recording) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除录屏文件 "${recording.fileName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用真实的删除API
    const response = await filesAPI.deleteRecording(recording.id)

    if (response.code === 200) {
      // 从列表中移除
      const index = recordingList.value.findIndex(item => item.id === recording.id)
      if (index > -1) {
        recordingList.value.splice(index, 1)
        pagination.total--
      }
      ElMessage.success('录屏文件删除成功')
    } else {
      throw new Error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除录屏文件失败:', error)
      ElMessage.error('删除录屏文件失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedRecordings.value.length === 0) {
    ElMessage.warning('请选择要删除的录屏文件')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRecordings.value.length} 个录屏文件吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用真实的批量删除API
    const ids = selectedRecordings.value.map(item => item.id)
    const response = await filesAPI.batchDeleteRecordings({ ids })

    if (response.code === 200) {
      // 从列表中移除选中的项
      selectedRecordings.value.forEach(recording => {
        const index = recordingList.value.findIndex(item => item.id === recording.id)
        if (index > -1) {
          recordingList.value.splice(index, 1)
        }
      })

      pagination.total -= selectedRecordings.value.length
      selectedRecordings.value = []

      ElMessage.success('批量删除成功')
    } else {
      throw new Error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 清理过期录屏
const cleanupOldRecordings = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清理过期的录屏文件吗？此操作不可恢复。',
      '确认清理',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    // 模拟清理API调用
    await new Promise(resolve => setTimeout(resolve, 2000))

    // 模拟清理结果
    const cleanedCount = Math.floor(Math.random() * 10) + 1
    ElMessage.success(`成功清理了 ${cleanedCount} 个过期录屏文件`)

    // 重新加载数据
    loadRecordings()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理过期录屏失败:', error)
      ElMessage.error('清理过期录屏失败')
    }
  } finally {
    loading.value = false
  }
}

// 显示设置对话框
const showSettingsDialog = () => {
  settingsDialogVisible.value = true
}

// 加载服务端存储配置
const loadServerStorageConfig = async () => {
  try {
    const response = await systemAPI.getSystemInfo()
    if (response.code === 200 && response.data) {
      if (response.data.fileStorage && response.data.fileStorage.recordingsPath) {
        storageSettings.storagePath = response.data.fileStorage.recordingsPath
      } else {
        storageSettings.storagePath = '未配置'
      }
    } else {
      storageSettings.storagePath = '获取失败'
    }
  } catch (error) {
    console.error('加载服务端存储配置失败:', error)
    storageSettings.storagePath = '获取失败'
  }
}

// 选择存储路径（获取默认路径）
const selectStoragePath = async () => {
  try {
    const response = await systemAPI.getSystemInfo()
    if (response.code === 200 && response.data.fileStorage) {
      storageSettings.storagePath = response.data.fileStorage.recordingsPath || './storage/recordings'
      ElMessage.success('已获取当前默认存储路径')
    }
  } catch (error) {
    console.error('获取默认存储路径失败:', error)
    ElMessage.error('获取默认存储路径失败')
  }
}

// 保存存储设置
const saveStorageSettings = async () => {
  if (!storageSettings.storagePath.trim()) {
    ElMessage.warning('请输入存储路径')
    return
  }

  try {
    // 调用更新存储路径API
    const response = await systemAPI.updateRecordingStoragePath({
      recordingsPath: storageSettings.storagePath
    })

    if (response.code === 200) {
      ElMessage.success('存储路径设置已保存')
      settingsDialogVisible.value = false
    } else {
      throw new Error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存存储设置失败:', error)
    ElMessage.error('保存存储设置失败')
  }
}

// 加载客户端列表
const loadClients = async () => {
  try {
    const response = await clientsAPI.getClients()
    if (response.code === 200) {
      clientList.value = response.data.list || []
    }
  } catch (error) {
    console.error('加载客户端列表失败:', error)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadClients()
  loadRecordings()
  loadServerStorageConfig()
})
</script>

<style scoped>
.recording-management-page {
  max-width: 1400px;
  margin: 0 auto;
}

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  color: #409EFF;
  font-size: 16px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.video-player {
  text-align: center;
}

.el-form--inline .el-form-item {
  margin-right: 20px;
  margin-bottom: 10px;
}

.action-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 8px;
  flex-wrap: nowrap;
  min-width: 180px;
  padding: 4px 0;
}

.action-buttons .el-button {
  flex-shrink: 0;
  min-width: 56px;
  height: 32px;
  padding: 6px 10px;
  font-size: 12px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-buttons .el-button .el-icon {
  margin-right: 4px;
  font-size: 12px;
}

.action-buttons .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 确保按钮文字不换行 */
.action-buttons .el-button span {
  white-space: nowrap;
}
</style>
